package com.example.musicplayer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;


/**
 * Created by asd on 2016/8/28.
 */
public class MusicShows extends Activity implements View.OnClickListener {
    private TextView tv_title;
    private TextView tv_artist;
    private SeekBar sb;
    private Intent intent;
    private ImageButton ib_play;
    private List<Music> data;
    private int a;
    private int musicId = 0;
    private ImageButton ibLove;
    private ImageButton ibLast;
    private ImageButton ibNext;
    private ImageButton ibList;
    private boolean flage = true;
    private Handler mHander;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_shows);
        local_data();
        init();
        dodo();
        MyListener();
    }

    private void MyListener() {
        //seekBar的滑动监听事件
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Message message = new Message();
                message.what = 0x126;
                message.arg1 = seekBar.getProgress();
                mHander.sendMessage(message);
                a = seekBar.getProgress();
            }
        });
        //图片按钮的监听
        ib_play.setOnClickListener(this);
        ibLast.setOnClickListener(this);
        ibList.setOnClickListener(this);
        ibLove.setOnClickListener(this);
        ibNext.setOnClickListener(this);
    }

    private void dodo() {

        if (data.get(musicId) != null) {
            Log.v("msg", musicId + "");
            tv_title.setText(data.get(musicId).getTitle());
            tv_artist.setText(data.get(musicId).getArtist());
            sb.setMax((int) data.get(musicId).getTime());

        }

    }

    private void init() {
        mHander = MainActivity.handler;
        //初始化XMl中的View
        intent = getIntent();
        musicId = intent.getIntExtra("musicId", 0);
        a = intent.getIntExtra("a", 0);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_artist = (TextView) findViewById(R.id.tv_artist);
        sb = (SeekBar) findViewById(R.id.sb);
        ibLove = (ImageButton) findViewById(R.id.ib_love);
        ibLast = (ImageButton) findViewById(R.id.ib_last);
        ibNext = (ImageButton) findViewById(R.id.ib_next);
        ibList = (ImageButton) findViewById(R.id.ib_list);
        ib_play = (ImageButton) findViewById(R.id.ib_play);
        new MyThread().start();
    }

    //设置歌曲名和作者
    private void SetText(Music music) {
        tv_title.setText(music.getTitle());
        tv_artist.setText(music.getArtist());
    }

    @Override
    public void onClick(View v) {
        final Message message = new Message();
        switch (v.getId()) {
            case R.id.ib_last:
                musicId--;
                if (musicId > 0) {
                } else {
                    musicId = data.size() - 1;
                }
                a = 0;
                break;
            case R.id.ib_list:
                //创建一个弹出对话框
                final AlertDialog.Builder dialog = new AlertDialog.Builder(MusicShows.this);
                //设置标题
                dialog.setTitle("音乐列表");
                //新建一个listView
                ListView listView = new ListView(this);
                //填充数据
                MyAdapter adapter = new MyAdapter();
                listView.setAdapter(adapter);
                //把listVIew填充到对话框中
                dialog.setView(listView);
                //显示对话框
                final AlertDialog alertDialog = dialog.show();
                //列表监听函数
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Message message1 = new Message();
                        message1.what = 0x125;
                        musicId = position;
                        message1.arg1 = position;
                        mHander.sendMessage(message1);
                        SetText(data.get(position));
                        alertDialog.dismiss();
                    }
                });
                break;
            case R.id.ib_love:
                new MyThread().start();
                break;
            case R.id.ib_next:
                message.what = 0x123;
                mHander.sendMessage(message);
                musicId++;
                SetText(data.get(musicId));
                a = 0;
                break;
            case R.id.ib_play:
                message.what = 0x124;
                mHander.sendMessage(message);
                break;
        }
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(MusicShows.this, R.layout.music_data, null);
                holder.txt_artist = (TextView) convertView.findViewById(R.id.tv_artist);
                holder.txt_title = (TextView) convertView.findViewById(R.id.tv_title);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.txt_artist.setText(data.get(position).getArtist());
            holder.txt_title.setText(data.get(position).getTitle());
            return convertView;
        }

        private class ViewHolder {
            TextView txt_artist;
            TextView txt_title;
        }
    }

    private class MyThread extends Thread {
        @Override
        public void run() {
            while (flage) {
                try {
                    sleep(1000);
                    a += 1000;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            sb.setProgress(a);
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                super.run();
            }
        }
    }

    private void local_data() {
        //查询媒体数据库
        ContentResolver resolver = MusicShows.this.getContentResolver();
        /**
         * Uri：这个Uri代表要查询的数据库名称加上表的名称。
         这个Uri一般都直接从MediaStore里取得，例如我要取所有歌的信息，
         就必须利用MediaStore.Audio.Media. EXTERNAL _CONTENT_URI这个Uri。
         *
         */
        Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

        ergodic(cursor);
    }

    private void ergodic(Cursor cursor) {
        data = new ArrayList<>();
//        cursor.moveToFirst();
        while (cursor.moveToNext()) {
            //歌曲文件的路径MediaStore.Audio.Media.DATA
            String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            //歌曲的歌手名MediaStore.Audio.Media.ARTIST
            String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
            //歌曲标题
            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
            long duration = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DURATION));//时长
            Music music = new Music();
            music.setTime(duration);
            music.setUrl(url);
            music.setTitle(title);
            music.setArtist(artist);
            data.add(music);
        }
    }
}
